#include "http.hpp"

// 统一所有的路径 indexurl都是wwwroot，如果是请求路径是"/"的话，就是path = indexurl + path + index.html 
std::string RequestStr(const HTTP::HttpRequest &req) {
    std::stringstream ss;
    ss << req._method << " " << req._path << " " << req._version << "\r\n";
    for (auto &it : req._params) {
        ss << it.first << ": " << it.second << "\r\n";
    }
    for (auto &it : req._headerfields) {
        ss << it.first << ": " << it.second << "\r\n";
    }
    ss << "\r\n";
    ss << req._body;   ///将请求提取 成回复的body
    return ss.str();
}
void Hello(const HTTP::HttpRequest &req, HTTP::HttpResponse *rsp) 
{
    /// 将请求的信息作为回复的body返回设置进回复中  functor(req,rsp);
    rsp->SetContent(RequestStr(req), "text/plain");
}
void Login(const HTTP::HttpRequest &req, HTTP::HttpResponse *rsp) 
{
    rsp->SetContent(RequestStr(req), "text/plain");
}
/// 这是用来向服务器推送文件的方法，服务器不返回body，只返回回复行和回复头字段
void PutFile(const HTTP::HttpRequest &req, HTTP::HttpResponse *rsp) 
{
    std::string pathname = indexurl + "/" + req._path;
    HTTP::Util::WriteToTheFile(pathname, req._body);
}
void DelFile(const HTTP::HttpRequest &req, HTTP::HttpResponse *rsp) 
{
    rsp->SetContent(RequestStr(req), "text/plain");
}
int main()
{
    HTTP::HttpServer server(8500,true);
    server.SetThreadCount(3);
    //server.SetBaseDir(WWWROOT);//设置静态资源根目录，告诉服务器有静态资源请求到来，需要到哪里去找资源文件
    server.Get("/hello", Hello);
    server.Post("/login", Login);
    server.Put("/1234.txt", PutFile);
    server.Delete("/1234.txt", DelFile);
    server.Start();
    return 0;
}